package echos

import (
	"net/http"
	"io/ioutil"
	jwt "github.com/dgrijalva/jwt-go"
	"github.com/labstack/echo"
	"github.com/labstack/echo/middleware"
)

type RestrictApiCb func(echo.Context) error

func http_Request_Body(r *http.Request) []byte {
	s, _ := ioutil.ReadAll(r.Body) //把body内容读入字符串s
    //fmt.Fprintf(w, "%s", s)        //在返回页面中显示内容。
    return s
}

/*
 注册回调函数: http url 映射到后端具体的事务处理函数
 回调函数返回处理结果到http client或者浏览器 
 */
func Restrict_GetCb_Registry(url string, /*cfg middleware.JWTConfig,*/
							 e *echo.Echo, cb RestrictApiCb) *echo.Group {

	// Configure middleware with the custom claims type
	config := middleware.JWTConfig{
		Claims:     &JwtCustomClaims{},
		SigningKey: []byte("secret"),
	}

	// Restricted group
	r := e.Group(url)
	r.Use(middleware.JWTWithConfig(config))
	r.GET("", (echo.HandlerFunc)(cb))
	return r
}

func Restrict_PostCb_Registry(url string, /*cfg middleware.JWTConfig,*/
							 e *echo.Echo, cb RestrictApiCb) *echo.Group {

	// Configure middleware with the custom claims type
	config := middleware.JWTConfig{
		Claims:     &JwtCustomClaims{},
		SigningKey: []byte("secret"),
	}

	// Restricted group
	r := e.Group(url)
	r.Use(middleware.JWTWithConfig(config))
	r.POST("", (echo.HandlerFunc)(cb))
	return r
}

func API_CbFunc_0(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*JwtCustomClaims)
	name := claims.Name
	// do something.....

	return c.JSON(http.StatusOK, echo.Map{
			"Username": name,
			"API": "api0",
			"Data": "nil",
	})
}

func API_CbFunc_1(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*JwtCustomClaims)
	name := claims.Name
	// do something.....

	return c.String(http.StatusOK, "api1/> Welcome "+name+"!")
}

func API_CbFunc_2(c echo.Context) error {
	user := c.Get("user").(*jwt.Token)
	claims := user.Claims.(*JwtCustomClaims)
	name := claims.Name
	// do something.....

	return c.String(http.StatusOK, "api2/> Welcome "+name+"!")
}